package com.xneure.enging.ui;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Type;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import com.xneure.enging.widget.impl.Entry;
import com.xneure.utils.FileUtil;
import com.xneure.utils.JsonUtil;
import com.xneure.utils.SpringUtil;

public class JsonConverter extends MappingJackson2HttpMessageConverter{
	@Override
	protected void writeInternal(Object object,Type type,HttpOutputMessage outputMessage) throws IOException,HttpMessageNotWritableException{
		if(object instanceof Entry){
			ServletServerHttpResponse sshr = (ServletServerHttpResponse)outputMessage;
			sshr.getHeaders().set("Content-Type","text/html");
			OutputStream body = outputMessage.getBody();
			Entry widget = (Entry)object;
			body.write(widget.getHtmlEle().toHtml().getBytes());
		}else if(object instanceof File || object instanceof byte[]){
			OutputStream body = outputMessage.getBody();
			if(object instanceof File){
				SpringUtil.getResponse().addHeader("Content-Disposition","attachment; filename=" + ((File)object).getName());
				body.write(FileUtil.readFile((File)object));
			}else if(object instanceof byte[]){
				body.write((byte[])object);
			}
		}else{
			if(outputMessage.getHeaders().getContentType().includes(MediaType.TEXT_HTML) && object instanceof String){
				outputMessage.getBody().write(((String)object).getBytes("utf-8"));
			}else{
				outputMessage.getBody().write(JsonUtil.toJson(object).getBytes("utf-8"));
			}
		}
	}
}
